package com.nopay.dxdwphone.ui.fragment.task;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.nopay.dxdwphone.base.BaseFragment;
import com.nopay.dxdwphone.bean.CommonResponse;
import com.nopay.dxdwphone.bean.request.DeleteCallTaskFromGroupRequest;
import com.nopay.dxdwphone.bean.request.GetCallTaskUnCallRequest;
import com.nopay.dxdwphone.bean.response.GetCallTaskCallResponse;
import com.nopay.dxdwphone.dialog.DialogDeleteCallTask;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.SinaRefreshView;
import java.util.ArrayList;
import java.util.List;
import com.nopay.dxdwphone.Constants;
import com.nopay.dxdwphone.R;
import com.nopay.dxdwphone.databinding.FragmentDialedBinding;

import com.nopay.dxdwphone.ui.adapter.DialedAdapter;
import com.nopay.dxdwphone.ui.ativity.CallTaskDetailActivity;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class DialedFragment extends BaseFragment<FragmentDialedBinding> {

    private CallTaskDetailActivity getParentActivity() {
        return ((CallTaskDetailActivity) getActivity());
    }

    private int getCallTaskId() {
        if(getParentActivity() == null) {
            return -1;
        }
        return getParentActivity().mCallTask.getId();
    }

    private List<GetCallTaskCallResponse.Data> dataList = new ArrayList<>();
    private int page = 1;
    private DialedAdapter adapter;

    @Override
    protected void loadData() {
        //添加头
        SinaRefreshView headerView = new SinaRefreshView(getActivity());
        headerView.setArrowResource(R.mipmap.arrow);
        headerView.setTextColor(0xff745D5C);
        binding.refreshLayout.setHeaderView(headerView);
        //添加底
        com.lcodecore.tkrefreshlayout.footer.LoadingView loadingView = new com.lcodecore.tkrefreshlayout.footer.LoadingView(getActivity());
        binding.refreshLayout.setBottomView(loadingView);

        binding.rvCall.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new DialedAdapter(dataList);

        binding.rvCall.setAdapter(adapter);
        binding.refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                page = 1;
                dataList.clear();
                requestCallData(() -> {
                    // TODO 处理请求结果
                    refreshLayout.finishRefreshing();
                    adapter.notifyDataSetChanged();
                });
            }

            @Override
            public void onLoadMore(final TwinklingRefreshLayout refreshLayout) {
                requestCallData(() -> {
                    refreshLayout.finishLoadmore();
                    adapter.notifyDataSetChanged();
                });
            }
        });

        // TODO 重拨
        binding.btnRecall.setOnClickListener(v -> getParentActivity().createTaskForRecall());

        binding.btnClearTask.setOnClickListener(v -> {
            // TODO 清空当前页数据
            if(dataList.size() == 0) {
                ToastUtils.showShort("当前无通话记录");
                return;
            }

            new DialogDeleteCallTask(getActivity()).setOnDeleteCallTaskConfirmListener(() -> {
                DeleteCallTaskFromGroupRequest bean = new DeleteCallTaskFromGroupRequest();
                bean.setPhone(SPUtils.getInstance().getString(Constants.SP_PHONE, ""));
                bean.setTaskId(getCallTaskId());
                bean.setType(1);

                RequestBody body = getRequestBody(bean);
                api.doDeleteCallTaskFromGroup(body).enqueue(new Callback<CommonResponse>() {
                    @Override
                    public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                        if (response.body() != null) {
                            if (Constants.RESULT_OK.equals(response.body().getCode())) {
                                ToastUtils.showShort("删除成功");
                                ((CallTaskDetailActivity) getActivity()).initCallCount();
                                binding.refreshLayout.startRefresh();
                            } else {
                                ToastUtils.showShort(response.body().getMsg());
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResponse> call, Throwable t) {
                        ToastUtils.showShort(getActivity().getResources().getString(R.string.call_api_error));
                    }
                });
            }).show("确定要删除所有通话记录吗？");
        });

        binding.refreshLayout.startRefresh();
    }

    private void requestCallData(OnRequestDataCompleteCallback callback) {
        String phone = SPUtils.getInstance().getString(Constants.SP_PHONE, "");
        GetCallTaskUnCallRequest request = new GetCallTaskUnCallRequest();
        request.setPhone(phone);
        request.setTaskId(getCallTaskId());
        request.setPageNum(page);
        request.setPageSize(50);

        RequestBody body = getRequestBody(request);
        api.doGetCallLogList(body).enqueue(new Callback<GetCallTaskCallResponse>() {
            @Override
            public void onResponse(@NonNull Call<GetCallTaskCallResponse> call, @NonNull Response<GetCallTaskCallResponse> response) {
                if (response.body() != null) {
                    if (Constants.RESULT_OK.equals(response.body().getCode())) {
                        List<GetCallTaskCallResponse.Data> callInfoList = response.body().getRows();
                        if(callInfoList != null && callInfoList.size() > 0) {
                            dataList.addAll(callInfoList);
                            page++;
                        }
                    } else {
                        ToastUtils.showShort(response.body().getMsg());
                    }
                }

                if(callback != null) callback.onComplete();
            }

            @Override
            public void onFailure(@NonNull Call<GetCallTaskCallResponse> call, @NonNull Throwable t) {
                if(callback != null) callback.onComplete();
                ToastUtils.showShort(getParentActivity().getResources().getString(R.string.call_api_error));
            }
        });
    }

    public interface OnRequestDataCompleteCallback {

        void onComplete();
    }
}
